package com.dure.fqllib;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by siqi on 16/6/2.
 *
 * @author siqi
 */
public class SignUtils {

    public static Map<String, ?> paramFilter(JSONObject json) {
        Map<String, Object> result = new HashMap<>();
        Iterator<?> objkey = json.keys();
        while (objkey.hasNext()) {
            String key = objkey.next().toString();
            Object value = json.opt(key);
            if (value == null || value.equals("") || value.equals(null) || key.equalsIgnoreCase("sign_type")
                    || key.equalsIgnoreCase("sign_info"))
                continue;
            if (value instanceof JSONObject) {
                if (!"parmMap".equalsIgnoreCase(key))
                    result.put(key, paramFilter((JSONObject) value));
                else
                    result.put(key, paramMapFilter((JSONObject) value));//对京东amount字段特殊处理
            } else
                result.put(key, value);
        }
        return result;
    }

    private static Map<String, ?> paramMapFilter(JSONObject json) {
        Map<String, Object> result = new HashMap<>();
        Iterator<?> objkey = json.keys();
        while (objkey.hasNext()) {
            String key = objkey.next().toString();
            Object value = json.opt(key);
            if (value == null || value.equals("") || value.equals(null) || key.equalsIgnoreCase("sign_type")
                    || key.equalsIgnoreCase("sign_info"))
                continue;
            if (value instanceof JSONObject) {
                result.put(key, paramFilter((JSONObject) value));
            } else
                result.put(key, value);
        }
        return result;
    }

    public static String buildLink(Map<String, ?> map) {
        ArrayList<String> keys = new ArrayList<>(map.keySet());
        Collections.sort(keys);
        int size = keys.size();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < size; i++) {
            String key = keys.get(i);
            Object o = map.get(key);
            String value = String.valueOf(o);
            if (o instanceof Map)
                value = "{" + buildLink((Map<String, ?>) o) + "}";
            if (i == size - 1)
                builder.append(key).append("=").append(value);
            else
                builder.append(key).append("=").append(value).append("&");
        }
        return builder.toString();
    }
}
